/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.rafkind.resrev.web.page.component;

import com.rafkind.resrev.dao.ReservationDao;
import com.rafkind.resrev.data.Reservation;
import com.rafkind.resrev.data.Status;
import com.rafkind.resrev.service.MailService;
import com.rafkind.resrev.web.Session;
import java.text.MessageFormat;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;

/**
 *
 * @author Fictional Hero
 */
public class ApproveDenyReservationPanel extends Panel {

  @SpringBean
  private ReservationDao reservationDao;
  
  @SpringBean
  private MailService mailService;
  
  public ApproveDenyReservationPanel(String id, 
      IModel<Reservation> model) {
    super(id, model);
    
    Reservation r = model.getObject();
    
    Link approveLink = new Link("approveLink") {
      @Override
      public void onClick() {
        Reservation r = (Reservation) ApproveDenyReservationPanel.this.getDefaultModelObject();
        r.setAuthorization(Status.APPROVED);
        r.setAuthorizor(((Session)getSession()).getCurrentUser());
        reservationDao.saveReservation(r);
        mailService.notifyApproved(r);
      }
    };
    String approveMessage = 
        MessageFormat.format(
          "return confirm(''Really approve {0}\\''s reservation for "
          + "{1} from {2,date,MMM dd, yyyy hh:mm aa} to {3,date,MMM dd, yyyy hh:mm aa}?'');",
            r.getReserver().getName(),
            r.getResource().getName(),
            r.getStart(),
            r.getEnd());
    
    approveLink.add(new AttributeAppender("onclick", new Model(approveMessage), ";"));
    add(approveLink);
    
    Link denyLink = new Link("denyLink") {
      @Override
      public void onClick() {
        Reservation r = (Reservation) ApproveDenyReservationPanel.this.getDefaultModelObject();
        r.setAuthorization(Status.DENIED);
        r.setAuthorizor(((Session)getSession()).getCurrentUser());
        reservationDao.saveReservation(r);
        mailService.notifyDenied(r);
      }
    };
    String denyMessage = 
        MessageFormat.format(
          "return confirm(''Really deny {0}\\''s reservation for "
          + "{1} from {2,date,MMM dd, yyyy hh:mm aa} to {3,date,MMM dd, yyyy hh:mm aa}?'');",
            r.getReserver().getName(),
            r.getResource().getName(),
            r.getStart(),
            r.getEnd());
    
    denyLink.add(new AttributeAppender("onclick", new Model(denyMessage), ";"));
    add(denyLink);
  }
}